//
//  ManagersViewController.m
//  zhiche--delivery
//
//  Created by LeeBruce on 16/10/18.
//  Copyright © 2016年 LeeBruce. All rights reserved.
//

#import "ManagersViewController.h"
#import "RootViewController.h"
#import "TopBackView.h"
#import "Common.h"
#import "QiniuSDK.h"
#import <UIImageView+WebCache.h>
#import "LoginViewController.h"
#import "WKProgressHUD.h"
#import "ZHPickView.h"


@interface ManagersViewController ()<UITextFieldDelegate,UINavigationControllerDelegate,UIImagePickerControllerDelegate,UIGestureRecognizerDelegate,ZHPickViewDelegate>

@property (nonatomic,strong) WKProgressHUD *hud;
@property (nonatomic,strong) NSMutableDictionary *dataDictionary;
@property (nonatomic,strong) UITextField *nameTextField;
@property (nonatomic,strong) UITextField *phoneTextField;

@property (nonatomic,strong) UITextField *companyTextField;
@property (nonatomic,strong) UITextField *emailTextField;


@property (nonatomic,strong) UIImageView *imagev;

@property (nonatomic,copy) NSString *token;
@property (nonatomic,copy) NSString *qiNiuKey;

@property (nonatomic,strong) UIScrollView *scrollView;

@property (nonatomic,strong) UIImageView * LoginImage;



@end

@implementation ManagersViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    
    self.qiNiuKey = @"";
//    self.valueString = @"";
    self.dataDictionary = [NSMutableDictionary dictionary];

    
    self.view.backgroundColor = [UIColor whiteColor];
    self.navigationController.interactivePopGestureRecognizer.delegate = (id)self;
    self.navigationController.interactivePopGestureRecognizer.enabled = YES;

    TopBackView *topBackView= [[TopBackView alloc]initViewWithFrame:CGRectMake(0, 0, screenWidth, 64) andTitle:@"账户管理"];
    
    [topBackView.rightButton setTitle:@"保存" forState:UIControlStateNormal];
    topBackView.rightButton.titleLabel.font = Font(14);
    [topBackView.rightButton setTitleColor:WhiteColor forState:UIControlStateNormal];
    
    [topBackView.rightButton addTarget:self action:@selector(confirmButton) forControlEvents:UIControlEventTouchUpInside];
    
    
    [topBackView.leftButton addTarget:self action:@selector(backAction) forControlEvents:UIControlEventTouchUpInside];
    [self.view addSubview:topBackView];
    self.view.backgroundColor = [UIColor whiteColor];

    
    [self initSubviews];
    [self initDataSource];

    self.hud = [WKProgressHUD showInView:self.view withText:@"" animated:YES];

    _LoginImage = [[UIImageView alloc]initWithFrame:CGRectMake(0, 0, Main_Width, Main_height)];
    _LoginImage.hidden = NO;
    //    _LoginImage.backgroundColor = WhiteColor;
    _LoginImage.image = [UIImage imageNamed:@"6"];
    [self.view addSubview:_LoginImage];



}


#pragma mark 获取个人信息 赋值
-(void)initDataSource
{
    
    //个人信息接口
    
    [Common requestWithUrlString:user_info contentType:application_json finished:^(id responseObj) {
        
        [self.hud dismiss:YES];
        
        if ([responseObj[@"success"] boolValue]) {
            
            
            self.dataDictionary = responseObj[@"data"];
            //            NSLog(@"%@",self.dataDictionary);
            //赋值
            [self getValueString];
        } else {
            
            [WKProgressHUD popMessage:responseObj[@"message"] inView:self.view duration:1.5 animated:YES];
            
        }
        
    } failed:^(NSString *errorMsg) {
        NSLog(@"%@",errorMsg);
        
        [self.hud dismiss:YES];
        
    }];
    
}

-(void)getValueString
{
    
    [self.hud dismiss:YES];
    
    
    if ([self.dataDictionary[@"pic"] isEqual:[NSNull null]]) {
        self.imagev.image = [UIImage imageNamed:@"personal_picture"];
    } else {
        //拼接图片url
        NSString *urlString = [NSString stringWithFormat:@"%@",self.dataDictionary[@"pic"]];
        
        //        [self.imagev sd_setImageWithURL:[NSURL URLWithString:urlString]];
        [self.imagev sd_setImageWithURL:[NSURL URLWithString:urlString] placeholderImage:[UIImage imageNamed:@"personal_picture"]];
    }
    
    
    NSString *name ;
    if ([self.dataDictionary[@"realName"] isEqual:[NSNull null]]) {
        name = @"";
    } else {
        name = [NSString stringWithFormat:@"%@",self.dataDictionary[@"realName"]];
        
    }
    
    self.nameTextField.text = name;
    
    NSString *company ;
    if ([self.dataDictionary[@"companyName"] isEqual:[NSNull null]]) {
        company = @"";
    } else {
        company = [NSString stringWithFormat:@"%@",self.dataDictionary[@"companyName"]];
        
    }
    
    self.companyTextField.text = company;
    

    if ([self.dataDictionary[@"email"] isEqual:[NSNull null]]) {
        
        self.emailTextField.text = @"";
    } else {
        self.emailTextField.text = [NSString stringWithFormat:@"%@",self.dataDictionary[@"email"]];
        
    }

    self.phoneTextField.text = [NSString stringWithFormat:@"%@",self.dataDictionary[@"phone"]];

}

-(void)initSubviews
{
    
    self.scrollView = [[UIScrollView alloc]initWithFrame:CGRectMake(0, 64, screenWidth, screenHeight)];
    [self.view addSubview:self.scrollView];
    
    
    // 头像试图
    
    UIView *pictureView = [self backViewWithFrame:CGRectMake(0, 0, screenWidth, 78) andString:@"头像" andWidth:0];
    
    self.imagev = [[UIImageView alloc]initWithFrame:CGRectMake(screenWidth - 9 - 10 - 14 - 50, 14, 50, 50)];
    self.imagev.layer.cornerRadius = 25;
    self.imagev.layer.masksToBounds = YES;
    [pictureView addSubview:self.imagev];
    
    [self.scrollView addSubview:pictureView];
    
    UITapGestureRecognizer *tap = [[UITapGestureRecognizer alloc]initWithTarget:self action:@selector(tapToGetPicture)];
    [pictureView addGestureRecognizer:tap];
    
    
    UIImageView *arrowImg = [[UIImageView alloc]initWithFrame:CGRectMake( screenWidth - 10 - 14, 32, 10, 14)];
    arrowImg.image = [UIImage imageNamed:@"personal_arrow"];
    [pictureView addSubview:arrowImg];
    
    // 用户名
    
    UIView *nameView = [self backViewWithFrame:CGRectMake(0, CGRectGetMaxY(pictureView.frame) + 10, screenWidth, cellHeight) andString:@"姓名"];
    [self.scrollView addSubview:nameView];
    self.scrollView.backgroundColor = GrayColor;
    
    self.nameTextField = [[UITextField alloc]initWithFrame:CGRectMake(screenWidth -  14 - 250, 5, 250, cellHeight)];
    self.nameTextField.delegate = self;
    self.nameTextField.font = Font(12);
    self.nameTextField.userInteractionEnabled = NO;
    self.nameTextField.textAlignment = NSTextAlignmentRight;
    [nameView addSubview:self.nameTextField];
    self.nameTextField.textColor = fontGrayColor;
    
    //手机号
    UIView *phoneView = [self backViewWithFrame:CGRectMake(0, CGRectGetMaxY(nameView.frame) , screenWidth, cellHeight) andString:@"电话"];
    [self.scrollView addSubview:phoneView];
    
    self.phoneTextField = [[UITextField alloc]initWithFrame:CGRectMake(screenWidth -  14 - 250, 5, 250, cellHeight)];
    self.phoneTextField.delegate = self;
    self.phoneTextField.font = Font(12);
    self.phoneTextField.userInteractionEnabled = NO;
    self.phoneTextField.textAlignment = NSTextAlignmentRight;
    [phoneView addSubview:self.phoneTextField];
    self.phoneTextField.textColor = fontGrayColor;
    
    //公司名称
    
    UIView *companyView = [self backViewWithFrame:CGRectMake(0, CGRectGetMaxY(phoneView.frame) , screenWidth, cellHeight) andString:@"公司名称"];
    [self.scrollView addSubview:companyView];
    
    self.companyTextField = [[UITextField alloc]initWithFrame:CGRectMake(screenWidth -  14 - 250, 5, 250, cellHeight)];
    self.companyTextField.delegate = self;
    self.companyTextField.font = Font(12);
    self.companyTextField.userInteractionEnabled = NO;
    self.companyTextField.textAlignment = NSTextAlignmentRight;
    [companyView addSubview:self.companyTextField];
    self.companyTextField.textColor = fontGrayColor;
    
    
    //邮箱
    
    UIView *emailView = [self backViewWithFrame:CGRectMake(0, CGRectGetMaxY(companyView.frame), screenWidth, cellHeight) andString:@"邮箱"];
    [self.scrollView addSubview:emailView];
    
    self.emailTextField = [[UITextField alloc]initWithFrame:CGRectMake(CGRectGetMinX(self.nameTextField.frame), 0, 250, cellHeight)];
    self.emailTextField.keyboardType = UIKeyboardTypeEmailAddress;
    self.emailTextField.delegate = self;
    self.emailTextField.font = Font(12);
    self.emailTextField.clearButtonMode = UITextFieldViewModeWhileEditing;
    self.emailTextField.textAlignment = NSTextAlignmentRight;
    [emailView addSubview:self.emailTextField];
    self.emailTextField.textColor = littleBlackColor;
    
      //
    UIButton *logoutButton = [UIButton buttonWithType:UIButtonTypeCustom];
    logoutButton.backgroundColor = WhiteColor;
    logoutButton.frame = CGRectMake(0, CGRectGetMaxY(emailView.frame) + 10, screenWidth - 0, cellHeight);
    [logoutButton setTitle:@"退出登录" forState:UIControlStateNormal];
        logoutButton.tag = 500;
    logoutButton.titleLabel.font = Font(13);
    [logoutButton addTarget:self action:@selector(logoutButtonAction) forControlEvents:UIControlEventTouchUpInside];
    [logoutButton setTitleColor:littleBlackColor forState:UIControlStateNormal];
    
    
    [self.scrollView addSubview:logoutButton];
    
}

//获取图片
-(void)tapToGetPicture
{
    [self photoButton];
    
}

-(void)confirmButton
{
    [self changePersonInfo];
    
}

-(void)changePersonInfo
{
    NSDictionary *dictionay = [NSDictionary dictionary];

    NSString *genderString;
    if ([self.dataDictionary[@"gender"] isEqual:[NSNull null]]) {
        genderString = @"";
        
    } else {
        genderString = self.dataDictionary[@"gender"];
        
    }
    
    
    NSString *birthdayString;
    if ([self.dataDictionary[@"birthday"] isEqual:[NSNull null]]) {
        birthdayString = @"";
        
    } else {
        birthdayString = self.dataDictionary[@"gebirthdaynder"];
    }
    
    
    if (_qiNiuKey.length > 0) {
        
    } else {
        
//        NSLog(@"%@",[NSString stringWithFormat:@"%@",_dataDictionary[@"picKey"]]);
        if ( [[NSString stringWithFormat:@"%@",_dataDictionary[@"picKey"]] isEqualToString:@"<null>"] || [self.dataDictionary[@"picKey"] isEqual:[NSNull class]]) {
            self.qiNiuKey = @"";
        } else {
            self.qiNiuKey = _dataDictionary[@"picKey"];
        }
    }
    
    //判断邮箱是否正确
    if ([self isValidateEmail:self.emailTextField.text] || [self.emailTextField.text isEqualToString:@""] ) {
        
        
    dictionay = @{@"name":self.nameTextField.text,
                  @"email":self.emailTextField.text,
                  @"gender": genderString,
                  @"birthday":birthdayString,
                  @"pic":self.qiNiuKey,
                  @"pwd":@" "
                  };
    
    
    Common *c = [[Common alloc]init];
    [c afPostRequestWithUrlString:user_modify parms:dictionay finishedBlock:^(id responseObj) {
        
        NSDictionary *dic = [NSJSONSerialization JSONObjectWithData:responseObj options:NSJSONReadingMutableLeaves error:nil];
        
        if ([dic[@"success"] boolValue]) {
            
            [WKProgressHUD popMessage:dic[@"message"] inView:self.view duration:1.5 animated:YES];
            
            //延迟执行
            dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(1 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
                
                
                [self backAction];
                
            });
            
            
        } else {
            [WKProgressHUD popMessage:dic[@"message"] inView:self.view duration:1.5 animated:YES];
        }
        
    } failedBlock:^(NSString *errorMsg) {
        NSLog(@"%@",errorMsg);
    }];
        
    } else {
        [WKProgressHUD popMessage:@"请填写正确的邮箱格式" inView:self.view duration:1.5 animated:YES];

    }

}

#pragma mark 退出登录
-(void)logoutButtonAction
{
    NSUserDefaults *userDefaults = [NSUserDefaults standardUserDefaults];
    [userDefaults setObject:nil forKey:@"login"];
    [userDefaults setObject:nil forKey:login_token];

    
    
    _LoginImage.hidden = NO;
    
    LoginViewController *loginVC = [[LoginViewController alloc]init];
    UINavigationController *loginNC = [[UINavigationController alloc]initWithRootViewController:loginVC];
    

    [self presentViewController:loginNC animated:YES completion:nil];

//    dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(0.5 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
//        
//        [self.navigationController popViewControllerAnimated:YES];
//        
//        //        [self presentViewController:loginNC animated:YES completion:nil];
//        
//    });
    
}
#pragma mark 邮箱地址的正则表达式
- (BOOL)isValidateEmail:(NSString *)email{
    NSString *emailRegex = @"[A-Z0-9a-z._%+-]+@[A-Za-z0-9.-]+\\.[A-Za-z]{2,4}";
    NSPredicate *emailTest = [NSPredicate predicateWithFormat:@"SELF MATCHES %@", emailRegex];
    return [emailTest evaluateWithObject:email];
}


#pragma mark 获取照片
-(void)photoButton
{
    __weak typeof(self) weakSelf = self;
    UIAlertController *alert = [UIAlertController alertControllerWithTitle:nil message:nil preferredStyle:UIAlertControllerStyleActionSheet];
    
    UIAlertAction *action1 = [UIAlertAction actionWithTitle:@"取消" style:UIAlertActionStyleCancel handler:nil];
    UIAlertAction *action2 = [UIAlertAction actionWithTitle:@"拍照" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
        
        
        [weakSelf getPictureFromCamera];
        
    }];
    UIAlertAction *action3 = [UIAlertAction actionWithTitle:@"从相册选取" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
        
        [weakSelf getPictureFromLibrary];
        
    }];
    
    [alert addAction:action1];
    [alert addAction:action2];
    [alert addAction:action3];
    
    
    [self presentViewController:alert animated:YES completion:nil];
    
}

#pragma mark 拍照
-(void)getPictureFromCamera
{
    UIImagePickerController *picker = [[UIImagePickerController alloc]init];
    picker.delegate = self;
    picker.allowsEditing = YES;
    picker.sourceType = UIImagePickerControllerSourceTypeCamera;
    
    [self presentViewController:picker animated:YES completion:nil];
}

#pragma mark 从相册选取
-(void)getPictureFromLibrary
{
    UIImagePickerController *picker = [[UIImagePickerController alloc]init];
    picker.delegate = self;
    picker.allowsEditing = YES;
    picker.sourceType = UIImagePickerControllerSourceTypePhotoLibrary;
    
    [self presentViewController:picker animated:YES completion:nil];
    
}


#pragma mark UIImagePickerControllerDelegate
-(void)imagePickerController:(UIImagePickerController *)picker didFinishPickingMediaWithInfo:(NSDictionary<NSString *,id> *)info
{
    [picker dismissViewControllerAnimated:YES completion:^{
        
        UIImage *image = [info objectForKey:UIImagePickerControllerEditedImage];
        
        self.imagev.image = image;
        
        self.hud = [WKProgressHUD showInView:self.view withText:@"" animated:YES];

        
        //上传服务器
        [self getTokenFromQN];
        
    }];
}

#pragma mark 从七牛获取Token
-(void)getTokenFromQN
{
    
    [Common requestWithUrlString:qiniu_token contentType:application_json finished:^(id responseObj) {
        if ([responseObj[@"success"] boolValue]) {
            
            self.token = responseObj[@"data"];
            [self uploadImageToQNWithData:[self getImageWith:self.imagev.image]];
        }
    } failed:^(NSString *errorMsg) {
        NSLog(@"%@",errorMsg);
    }];
    
    
}

-(void)uploadImageToQNWithData:(NSData *)data
{
    
    QNUploadManager *upManager = [[QNUploadManager alloc]init];
    
    QNUploadOption *uploadOption = [[QNUploadOption alloc]initWithMime:nil progressHandler:^(NSString *key, float percent) {
        
    } params:nil checkCrc:NO cancellationSignal:nil];
    
    [upManager putData:data key:nil token:self.token complete:^(QNResponseInfo *info, NSString *key, NSDictionary *resp) {
        
        [self.hud dismiss:YES];

        
        self.qiNiuKey = resp[@"key"];
        
        
    } option:uploadOption];
}


-(NSData *)getImageWith:(UIImage *)image
{
    NSData *data = nil;
    if (UIImagePNGRepresentation(image)) {
        
        data = UIImageJPEGRepresentation(image, 1);
        
        
    } else {
        data = UIImagePNGRepresentation(image);
        
        
    }
    
    return data;
}



#pragma mark UITextFieldDelegate

-(void)textFieldDidBeginEditing:(UITextField *)textField
{
    
    if (textField == self.emailTextField) {
        
        [UIView animateWithDuration:0.3 animations:^{
            /* 计算偏移量 */
            
            CGFloat height = 252;
            UIButton *button = (UIButton *)[self.view viewWithTag:500];
            CGFloat offsetHeight = CGRectGetMaxY(button.frame) - (Main_height - height- 64);
            
            
            if (offsetHeight > 0) {
                self.scrollView.contentInset = UIEdgeInsetsMake(-offsetHeight , 0, 0, 0);
                
            }
            
        } completion:^(BOOL finished) {
            
        }];
        
    }
    
}


-(void)textFieldDidEndEditing:(UITextField *)textField
{
    
    if (textField == self.emailTextField) {

        [UIView animateWithDuration:0.3 animations:^{
            
            self.scrollView.contentInset = UIEdgeInsetsMake(0, 0, 0, 0);
            
        } completion:^(BOOL finished) {
            
        }];
    }
    
}



-(BOOL)textField:(UITextField *)textField shouldChangeCharactersInRange:(NSRange)range replacementString:(NSString *)string
{
    if ([string isEqualToString:@"\n"]) {
        [textField resignFirstResponder];
        return NO;
    }
    return YES;
}



-(BOOL)textFieldShouldReturn:(UITextField *)textField
{
    [textField resignFirstResponder];
    return YES;
}


-(UIView *)backViewWithFrame:(CGRect)frame andString:(NSString *)string andWidth:(float)width
{
    UIView *view = [[UIView alloc]initWithFrame:frame];
    view.backgroundColor = WhiteColor;
    UILabel *label = [[UILabel alloc]initWithFrame:CGRectMake(18, frame.size.height/2 - 10, 100, 20)];
    label.text = string;
    label.font = Font(13);
    label.textColor = littleBlackColor;
    
    
    
    UILabel *label1 = [[UILabel alloc]initWithFrame:CGRectMake(width,frame.size.height - 0.5, screenWidth , 0.5)];
    label1.backgroundColor = LineGrayColor;
    
    [view addSubview:label1];
    
    //    [view addSubview:imageV];
    [view addSubview:label];
    [self.scrollView addSubview:view];
    
    
    //    dispatch_async(dispatch_get_global_queue(0, 0), ^{
    //        // 处理耗时操作的代码块...
    //
    //        //通知主线程刷新
    //        dispatch_async(dispatch_get_main_queue(), ^{
    //            //回调或者说是通知主线程刷新，
    //        });
    //
    //    });
    
    
    return  view;
    
}

-(UIView *)backViewWithFrame:(CGRect)frame andString:(NSString *)string
{
    UIView *view = [[UIView alloc]initWithFrame:frame];
    view.backgroundColor = WhiteColor;
    UILabel *label = [[UILabel alloc]initWithFrame:CGRectMake(18, frame.size.height/2 - 10, 100, 20)];
    label.text = string;
    label.font = Font(13);
    label.textColor = littleBlackColor;
    
    
    
    UILabel *label1 = [[UILabel alloc]initWithFrame:CGRectMake(18,frame.size.height - 0.5, screenWidth , 0.5)];
    label1.backgroundColor = LineGrayColor;
    
    [view addSubview:label1];
    
    //    [view addSubview:imageV];
    [view addSubview:label];
    [self.scrollView addSubview:view];
    
    
    //    dispatch_async(dispatch_get_global_queue(0, 0), ^{
    //        // 处理耗时操作的代码块...
    //
    //        //通知主线程刷新
    //        dispatch_async(dispatch_get_main_queue(), ^{
    //            //回调或者说是通知主线程刷新，
    //        });
    //
    //    });
    
    
    return  view;
    
}

-(void)viewWillAppear:(BOOL)animated{
    
    
    _LoginImage.hidden = YES;
    self.navigationController.navigationBarHidden = YES;
    
    RootViewController *rootVC = [RootViewController defaultsTabBar];
    [rootVC setTabBarHidden:YES];
    
    NSNotificationCenter *notification = [NSNotificationCenter defaultCenter];
    [notification addObserver:self selector:@selector(popSelf) name:@"dismiss" object:nil];
    
}

-(void)popSelf
{
    [self .navigationController popViewControllerAnimated:NO];
}


-(void)backAction
{
    
    [self.navigationController popViewControllerAnimated:YES];
    
}


- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
